package com.wecloud.core.action.bussiness;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;

import org.springframework.beans.factory.annotation.Autowired;

import com.wecloud.core.action.impl.BaseTransCfmAction;
import com.wecloud.core.constant.ErrorMsg;
import com.wecloud.core.constant.WeContext;
import com.wecloud.core.data.jnl.JnlService;
import com.wecloud.core.exception.WeException;
import com.wecloud.core.user.WeUser;
import com.wecloud.redis.service.RedisService;

import scala.sys.process.processInternal;

/**
 * 使用密码
 * @author qq374
 *
 */
public class PassLoginAction extends BaseTransCfmAction{
    @Autowired
    private JnlService jnlService;//mysql
    @Autowired
	private RedisService redisService;//redis
	@Override
	public void excute(WeContext context)  throws WeException{
		String userName = context.getString("userName");
		String passWord = context.getString("passWord");
		String jSessionId = context.getString("JSESSIONID");
		//通过cookie中sessionid登陆
		WeUser user = null;
		Map map = null;
		Map r = new HashMap();
		if(!"".equals(jSessionId)){
			user = redisService.get(jSessionId);
			if(user == null){
				throw new WeException(ErrorMsg.Error_0003);
			}
			user.setLoginTime(new Date());//重设登陆时间
			redisService.add(jSessionId, user);//更新redis里用户信息
			r.put("userId", user.getUserId());
			r.put("userName", user.getUserName());
			context.setUser(user);
		}
		if("".equals(jSessionId) && !"".equals(userName) && !"".equals(passWord)){
			Map param = new HashMap();
			param.put("userName", userName);
			//passWord要做解密操作
			param.put("passWord", passWord);
			map = jnlService.queryForObject("user.userInfo",param);
			if(map == null){
				throw new WeException(ErrorMsg.Error_0001);
			}
			String sessionid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
			user = new WeUser();
			user.setUserId((String)map.get("userid"));
			user.setUserName((String)map.get("userName"));
			user.setSessionId(sessionid);
			redisService.add(sessionid, user);
			context.setUser(user);
			Cookie cookie = new Cookie("JSESSIONID",sessionid);
			context.getResp().addCookie(cookie);
//			context.setData("JSESSIONID", sessionid);
			r.put("userId", user.getUserId());
			r.put("userName", user.getUserName());
			r.put("JSESSIONID", sessionid);
		}
		if(user == null){
			throw new WeException(ErrorMsg.Error_0001);
		}
		context.setData("content", r);
	}
}
